<template>
    <div>
        <div class="crop-demo">
            <div class="crop-demo-image" v-if="cropImgage">
                <img :src="cropImgage" class="pre-img"  :style="cropStyle"/>
                <div class="action" @click="handleRemove">删除</div>
            </div>
            <div class="crop-demo-btn" :style="cropStyle" v-else>
                <input class="crop-input" :style="cropStyle" type="file" name="image" accept="image/*" @change="setImage" />
                <i class="i-plus">+</i>
            </div>
        </div>

        <el-dialog title="裁剪图片" :append-to-body="append" :close-on-click-modal= "false" :visible.sync="dialogVisible" width="30%">
            <vue-cropper
                ref="cropper"
                :src="imgSrc"
                :aspectRatio = "aspectRatio"
                :ready="cropImage"
                :zoom="cropImage"
                :cropmove="cropImage"
                style="width:100%;height:300px;"
            ></vue-cropper>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelCrop">取 消</el-button>
                <el-button type="primary" @click="handleUpload">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import VueCropper from 'vue-cropperjs'
import 'cropperjs/dist/cropper.css'
import util from '@/utils/util'
import { getUploadToken, replaceUploadItem, addUploadItem } from '@/api/upload/upload'
import { delStorageList, getStorageDirectorySelect } from '@/api/upload/storage'
export default {
    name: 'upload',
    components: { VueCropper },
    props: {
        type: {
            type: String,
            default: ''
        },
        aspectRatio: { 
            type: Number,
            default: 1 / 1
        },
        defaultImage: { 
            type: String, 
            default: ''
        }

    },
    data: function() {
        return {
            defaultUrl: require('@/assets/image/image.png'),
            append:true,
            file: {},
            imgSrc: '',
            cropImgage: '',
            dialogVisible: false,
            cropStyle: {
                width: "90px",
                height: "160px",
                'line-height': "160px",
            },
            storageId: 0,
            moduleName: '',
            replaceId: 0,
            updateToken: true,
            token: {},
            params: {},
            uploadUrl: '',
            parentId: -1,
            parentData: [],
            parentProps: {
                value: 'storage_id',
                label: 'name',
                children: 'children',
                checkStrictly: true,
                emitPath: false
            }
        };
    },
    components: {
        VueCropper
    },
    created() {
        this.cropImgage = this.defaultImage ? this.defaultImage : ''
        if(this.aspectRatio>1) {
            this.cropStyle.width = 120 * this.aspectRatio + "px"
            this.cropStyle.height = "120px"
            this.cropStyle.lineHeight = "120px"
        } else {
            this.cropStyle.width = 160 * this.aspectRatio * 1.5 + "px"
            this.cropStyle.height = "160px"
            this.cropStyle.lineHeight = "160px"
        }
        this.getToken()
        
    },
    watch: {
        defaultImage: {
            deep: true,
            handler(val) {
                this.handleSetPreview(val)
            }
        }
    },
    methods: {
        // 获取 Token
        getToken() {
            // 检测Token是否过期
            const nowTime = Math.round(new Date() / 1000) + 100
            if (this.token.expires !== 0 && nowTime > this.token.expires) {
                this.updateToken = true
            }

            return new Promise(resolve => {
                // 是否需要更新
                if (!this.updateToken) {
                return resolve()
                }

                this.params = {}
                if (this.replaceId) {
                    replaceUploadItem(this.replaceId)
                        .then(res => {
                            this.token = res.data || {}
                            this.uploadUrl = this.token.token.upload_url.upload_url
                            this.updateToken = false
                            resolve()
                    })
                } else {
                    getUploadToken(this.moduleName)
                        .then(res => {
                            this.token = res.data || {}
                            this.uploadUrl = this.token.token.upload_url.upload_url
                            this.updateToken = false
                            resolve()
                    })
                }
            })
        },
        handleRemove() {
            this.file = {}
            this.cropImgage = ""
        },
        setImage(e) {
            this.file = e.target.files[0];
            if (!this.file.type.includes('image/')) {
                return;
            }
            const reader = new FileReader();
            reader.onload = event => {
                this.dialogVisible = true;
                this.imgSrc = event.target.result;
                this.$refs.cropper && this.$refs.cropper.replace(event.target.result);
            };
            reader.readAsDataURL(this.file);



        },
        cropImage() {
            this.cropImgage = this.$refs.cropper.getCroppedCanvas().toDataURL();
        },
        cancelCrop() {
            this.dialogVisible = false
            this.cropImgage = ''
        },
        handleUpload() {
            let self = this
            const fielMaxSize = util.stringToByte(this.token.file_size)
            console.log(this.file)
            if (fielMaxSize > 0 && this.file.size > fielMaxSize) {
                this.$message.error(`上传资源大小不能超过 ${this.token.file_size}`)
                return false
            }

            const suffix = this.file.name.toLowerCase().split('.').splice(-1).toString()
            const checkSuffix = this.token.file_ext + ',' + this.token.image_ext
            if (checkSuffix.indexOf(suffix) === -1) {
                this.$message.error('上传资源的文件后缀不允许上传')
                return false
            }

            // 生成上传请求参数
            let param = this.token.token.upload_url.param
            param.forEach(value => {
                if (value.name === 'file') {
                    return
                }

                // 填入接口返回的参数
                this.params[value.name] = Object.prototype.hasOwnProperty.call(this.token.token, value.name)
                    ? this.token.token[value.name]
                    : value.default

                /**
                 * 替换资源编号不存在时表示上传新资源
                 * 此时需要对部分请求参数做特殊处理,而替换资源时不需要做处理
                 */
                if (!this.replaceId) {
                    if (value.name === 'x:filename') {
                        this.params['x:filename'] = this.file.name
                    }

                    if (value.name === 'x:parent_id') {
                        this.params['x:parent_id'] = 0
                        if (this.storageId !== null) {
                        this.params['x:parent_id'] = this.storageId
                        } else {
                        this.params['x:parent_id'] = this.parentId <= 0 ? 0 : this.parentId
                        }
                    }

                    if (value.name === 'key') {
                        const fileName = util.guid()
                        this.params.key = `${this.token.token.dir}${fileName}.${suffix}`
                    }
                }
            })
            if (this.token.token.upload_url.module === 'careyshop') {
                this.params.token = util.cookies.get('token')
                this.params.appkey = this.$baseConfig.APP_KEY
                this.params.timestamp = Math.round(new Date() / 1000) + 100
                this.params.format = 'json'
                this.params.method = 'add.upload.list'
                this.params.sign = util.getSign({ ...this.params })
            }    
            // 本地上传所需要的权限参数
            var formData = new FormData()
            Object.keys(this.params).forEach((key) => {
                formData.append(key, this.params[key]);
            });
            formData.append('file', this.file)
            addUploadItem(formData).then(response => {
                if (response.data) {
                    self.dialogVisible = false
                    self.$emit('upload-success',response.data)
                }
            })
        },
        handleError() {
            this.$notify.error({
                title: '上传失败',
                message: '图片上传接口上传失败，可更改为自己的服务器接口'
            });
        },
        handleSetPreview(val) {
            this.cropImgage  =  val ? val : this.defaultUrl
        }
    }
};
</script>

<style lang="scss">
.content-title {
    font-weight: 400;
    line-height: 50px;
    margin: 10px 0;
    font-size: 22px;
    color: #1f2f3d;
}

.crop-demo {
    display: flex;
    align-items: flex-end;
    &-image {
        position: relative;
        .pre-img {
            width: 100px;
            height: 100px;
            background: #f8f8f8;
            border: 1px solid #eee;
            border-radius: 5px;
        }
        .action {
            position:absolute;
            bottom: 16px;
            background-color:#000;
            color: #fff;
            font-size: 18px;
            opacity: .5;
            height: 20px;
            width: 100%
        }
    }

}
.crop-demo-btn {
    position: relative;
    width: 240px;
    height: 135px;
    line-height: 135px;
    padding: 0 20px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    color: #fff;
    font-size: 14px;
    border-radius: 5px;
    box-sizing: border-box;
    text-align: center;
    .i-plus{
        font-size: 40px;
        color: #8c939d;
        /* left: 41%; */
        /* font-weight: bold; */
    }
}
.crop-input {
    position: absolute;
    width: 240px;
    height: 135px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}


</style>
